package com.streamer.app.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.streamer.app.R
import com.streamer.app.bean.MessageBean

class DanmakuAdapter(
    private val messages: MutableList<MessageBean>
) : RecyclerView.Adapter<DanmakuAdapter.MessageVH>() {

    class MessageVH(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val ivAvatar: ImageView = itemView.findViewById(R.id.iv_avatar)
        val tvName: TextView = itemView.findViewById(R.id.tv_name)
        val tvContent: TextView = itemView.findViewById(R.id.tv_content)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MessageVH {
        val v = LayoutInflater.from(parent.context).inflate(R.layout.item_danmaku_message, parent, false)
        return MessageVH(v)
    }

    override fun onBindViewHolder(holder: MessageVH, position: Int) {
        val item = messages[position]
        holder.tvName.text = item.senderName
        holder.tvContent.text = item.content
        Glide.with(holder.ivAvatar)
            .load(item.avatar)
            .transform(CircleCrop())
            .into(holder.ivAvatar)
    }

    override fun getItemCount(): Int = messages.size

    fun append(item: MessageBean) {
        messages.add(item)
        notifyItemInserted(messages.size - 1)
    }

    fun setAll(items: List<MessageBean>) {
        messages.clear()
        messages.addAll(items)
        notifyDataSetChanged()
    }
} 